<template>
  <div class="mars-main-view" id="mars-main-view">
    <div id="centerDiv" class="centerDiv-container">
      <splitpanes>
        <pane min-size="25">
          <DMap :isMainViewer="true" :options="mapOptions" :mapKey="viewerId" @onload="mapOnload" />
        </pane>
        <pane min-size="25" v-if="isInteractive">
          <DMap :isMainViewer="false" :options="mapOptions" :mapKey="rightViewerId" @onload="map2Onload" />
        </pane>
      </splitpanes>
    </div>
    <template v-if="loaded">
      <template v-for="comp in widgets" :key="comp.key">
        <Widget v-if="openAtStart.includes(comp.name) && comp.visible" v-model:visible="comp.visible" :widget="comp" />
      </template>
    </template>
  </div>
</template>

<script setup>
/**
 * 渲染主入口
 */
import { computed, onBeforeUnmount, provide, readonly, ref, toRaw, watch } from "vue"
import { useWidget, useWidgetStore } from "@/common/store/widget"
import DMap from "@/components/de-work/de-map.vue"
import Widget from "./widget.vue"
import { entityKeys } from "@/common/symbolKeys"
import { useStore } from "vuex"
import { usePicker } from "@/common/uses/use-picker"
import {
  mountToWindow,
  syncViewer,
  unsyncViewer,
  viewerId,
  rightViewerId, initSelectedStateIcon
} from "@/components/de-work/map"
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import { useLayer } from "@/common/uses/use-layer"
import { registerLayers } from "@/common/layerCfg"


let layerManager

const store = useStore()
const showEditor = (options) => {
  const {
    data,
    name
  } = options
  if (!isActivate(name)) {
    activate({
      name,
      data
    })
  } else {
    updateWidget(name, {
      data
    })
  }
}

const widgetStore = useWidgetStore()
const {
  activate,
  disable,
  isActivate,
  updateWidget
} = useWidget()
const widgets = computed(() => widgetStore.state.widgets)
const openAtStart = computed(() => widgetStore.state.openAtStart)

const props = defineProps({
  mapOptions: Object
})

const isInteractive = computed(() => store.state.setting.global.isInteractive)
watch(isInteractive, (v) => {
  if (!v) {
    unsyncViewer(mapInstance)
  }
})

let mapInstance = null
provide("getMapInstance", () => {
  return mapInstance
})

// 当前鼠标左键拾取的实体信息
let leftClickTarget = null

mountToWindow({
  store,
  showEditor,
  disableWidget: disable,
  tooltipAutoHide: true
})

provide(entityKeys.LEFT_CLICK_TARGET, () => {
  return leftClickTarget
})

let rightClickTarget = null
provide(entityKeys.RIGHT_CLICK_TARGET, () => {
  return rightClickTarget
})

// 绑定全局鼠标左击、右击、移动事件
const mountGlobalEvent = (viewer) => {
  viewer.on(DE.MouseEventType.CLICK, (e) => {
    store.commit("common/setCurrentClickInfo", {
      ...e
    })
  })
  viewer.on(DE.MouseEventType.MOUSE_MOVE, (e) => {
    store.commit("common/setMovingMouseInfo", {
      ...e
    })
  })
  viewer.on(DE.MouseEventType.RIGHT_CLICK, (e) => {
    store.commit("common/setCurrentRightClickInfo", {
      ...e
    })
  })
}
const isAttackLineEndPositionPick = computed(() => store.state.event.isAttackLineEndPositionPick) // 是否进行位置拾取

const currentClickInfo = computed(() => store.state.common.currentClickInfo) // 正在编辑的对象
watch(currentClickInfo, (value) => {
  onGlobalClickChange(toRaw(value))
})

// 全局左击事件监听
const onGlobalClickChange = (clickInfo) => {
  const {
    feature,
    instanceId,
    layer,
    overlay,
    position,
    surfacePosition,
    target,
    wgs84Position,
    wgs84SurfacePosition,
    windowPosition
  } = clickInfo
  // 依赖注入方式修改全局左击对象
  leftClickTarget = target // target is the entity of scene.pick(position)
  const selectedIcon = window?.$selectedIcon
  if (!leftClickTarget || !leftClickTarget.id || !overlay || overlay?.type !== "billboard") {
    selectedIcon.show = false
  } else {
    // 如果选择实体为部署装备，更新Picker
    overlay && usePicker(overlay?.position, true)
  }

  if (overlay) {
    // 如果左击对象是Overlay且可编辑，则进入编辑状态
    if (overlay.hasEdit && !overlay.isEditing) {
      overlay.startEditing()
    }
  }
}

// 全局鼠标移动事件监听
const movingMouseInfo = computed(() => store.state.common.movingMouseInfo) // 正在编辑的对象
watch(movingMouseInfo, (value) => {
  onGlobalMovingInfoChange(toRaw(value))
})

const onGlobalMovingInfoChange = (e) => {
  const entity = e?.target?.id
  const overlay = e?.overlay
  if (entity && overlay && overlay.hasEdit && overlay.isEditing) {
    usePicker(entity.position, true)
  }
  if (overlay && overlay.hasEdit && !overlay.isEditing && e.windowPosition && window.$tooltipAutoHide) {
    mapInstance.tooltip.showAt(e.windowPosition, "左击编辑，右击菜单")
  }
  if (((!overlay || !entity) && window.$tooltipAutoHide) || !e.surfacePosition || !e.windowPosition) {
    mapInstance.tooltip.hide()
  }
}

// 全局右击事件监听
const rightClickInfo = computed(() => store.state.common.currentRightClickInfo) // 正在编辑的对象
watch(rightClickInfo, (value) => {
  onGlobalRightClickChange(toRaw(value))
})
const onGlobalRightClickChange = (clickInfo) => {
  const {
    overlay,
    target
  } = clickInfo
  const selectedIcon = window?.$selectedIcon
  rightClickTarget = target
  if (!rightClickTarget || !rightClickTarget.id || !overlay || overlay?.type !== "billboard") {
    if (selectedIcon) {
      selectedIcon.show = false
    }
  } else {
    // 如果选择实体为部署装备，更新Picker
    overlay && usePicker(overlay?.position, true)
  }
}

const emit = defineEmits(["mapLoaded"])

const loaded = ref(false)
const mapOnload = (viewer) => {
  console.log("viewer构造完成", viewer)
  viewer.tooltip.enable = true
  mapInstance = viewer
  /**
   * 全局挂载选中的框选图标
   */
  initSelectedStateIcon(viewer, { context: this })
  // 注册图层（右键菜单、图层组、事件的注册）
  layerManager = registerLayers(viewerId, {
    viewer,
    context: viewer,
    store,
    showEditor,
    disable
  })
  mountGlobalEvent(viewer)
  emit("mapLoaded", mapInstance)
  loaded.value = true
}

/**
 *
 * @param {DE.Viewer} viewer
 */
const map2Onload = (viewer) => {
  console.log("map2---", viewer)
  syncViewer(mapInstance, viewer, this)
  const equipPlotLayer = useLayer("equipPlotLayer2", { viewer })
}

onBeforeUnmount(() => {
  layerManager && layerManager.removeAllLayers()
})
</script>

<style lang="less" scoped>
.mars-main-view {
  display: flex;
  height: 100%;
  width: 100%;
  position: relative;

  :deep(.splitpanes--vertical > .splitpanes__splitter) {
    min-width: 3px;
  }
}

.centerDiv-container {
  height: 100%;
  width: 100%;
  overflow: hidden;
}
</style>
